package competition.cig.cs478;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import ch.idsia.ai.agents.Agent;
import ch.idsia.ai.agents.Agent.AGENT_TYPE;
import ch.idsia.mario.engine.sprites.Mario;
import ch.idsia.mario.environments.Environment;

import competition.cig.cs478.backprop.Network;
import competition.cig.cs478.backprop.NetworkAdapter;
import competition.cig.robinbaumgarten.AStarAgent;

public class CS478_Human_Backprop_Learner extends KeyAdapter implements Agent {

	private boolean[] Action = null;
	private Network network;
	private NetworkAdapter networkAdapter;
	private Agent aStarAgent;
	private double learningRate;
	private double momentum;
	
	public CS478_Human_Backprop_Learner(Network network) {
		this.network = network;
		this.networkAdapter = new NetworkAdapter();
		this.learningRate = 0.01;
		this.momentum = 0.0;
	}
	
	@Override
	public boolean[] getAction(Environment observation) {
		network.update(networkAdapter.getInput(observation));
		network.backPropagate(networkAdapter.getTargets(Action), learningRate, momentum);
		return Action;
	}

	@Override
	public String getName() {
		return "CS478_Human_Backprop_Learner : LR=" + learningRate + " M=" + momentum + " ";
	}

	@Override
	public AGENT_TYPE getType() {
		return AGENT_TYPE.HUMAN;
	}
	
	 public void keyPressed (KeyEvent e)
    {
        toggleKey(e.getKeyCode(), true);
        System.out.println("sdf");
    }

    public void keyReleased (KeyEvent e)
    {
        toggleKey(e.getKeyCode(), false);
    }
	
	private void toggleKey(int keyCode, boolean isPressed)
    {
        switch (keyCode) {
            case KeyEvent.VK_LEFT:
                Action[Mario.KEY_LEFT] = isPressed;
                break;
            case KeyEvent.VK_RIGHT:
                Action[Mario.KEY_RIGHT] = isPressed;
                break;
            case KeyEvent.VK_DOWN:
                Action[Mario.KEY_DOWN] = isPressed;
                break;

            case KeyEvent.VK_S:
                Action[Mario.KEY_JUMP] = isPressed;
                break;
            case KeyEvent.VK_A:
                Action[Mario.KEY_SPEED] = isPressed;
                break;
        }
    }

	@Override
	public void reset() {
		Action = new boolean[Environment.numberOfButtons];
	}

	@Override
	public void setName(String name) {
		aStarAgent.setName(name);
	}

}
